package org.acghub.mtdb.xmlgen.visitor;

import org.acghub.mtdb.common.Bean;
import org.acghub.mtdb.common.Var;
import org.acghub.mtdb.common.Visitor;
import org.acghub.mtdb.common.type.TypeBaseCollection;
import org.acghub.mtdb.common.type.TypeBaseMap;
import org.acghub.mtdb.common.type.TypeBasePrimitives;
import org.acghub.mtdb.core.Logs;
import org.acghub.mtdb.util.StringUtil;

import java.io.PrintStream;
import java.util.Objects;

/**
 * @author zhouhe
 */
public class VarSetterVisitor implements Visitor {
    private final Var var;
    private final PrintStream ps;
    private final String prefix;

    public VarSetterVisitor(Var var, PrintStream ps, String prefix) {
        this.var = var;
        this.ps = ps;
        this.prefix = prefix;
    }

    @Override
    public void visit(TypeBasePrimitives type) {
        String method = "set" + StringUtil.upperFirstChar(var.getName());
        ps.printf(prefix + String.format("public %s %s(%s v) {\n", var.getParent().getName(), method, type.javaInterfaceType()));
        ps.printf(StringUtil.concat(prefix, StringUtil.TAB) + "%s _verify_ = this._verify_unsafe_(%s, %s);\n", Runnable.class.getName(), StringUtil.quote(method), "false");
        ps.printf(StringUtil.concat(prefix, StringUtil.TAB) + "if (%s.equals(this.%s, v)) {\n", Objects.class.getName(), var.getName());
        ps.println(StringUtil.concat(prefix, StringUtil.tab(2)) + "return this;");
        ps.println(StringUtil.concat(prefix, StringUtil.TAB) + "}");
        ps.printf(StringUtil.concat(prefix, StringUtil.TAB) + "%s.simple(this, %s, this.%s, _verify_);\n",
                Logs.class.getName(), StringUtil.quote(var.getName()), var.getName());
        ps.println(StringUtil.concat(prefix, StringUtil.TAB) + "this." + var.getName() + " = v;");
        ps.println(StringUtil.concat(prefix, StringUtil.TAB) + "return this;");
        ps.println(prefix + "}");

    }

    @Override
    public void visit(TypeBaseCollection type) {

    }

    @Override
    public void visit(TypeBaseMap type) {

    }

    @Override
    public void visit(Bean bean) {

    }
}
